# -*- coding: UTF-8 -*-

from datetime import datetime
import sys
from sqlalchemy import and_,  func, or_
from typing import Dict, List, Any, Generator

from sqlalchemy import Boolean, Column, DateTime, Integer, String, Index, Table, ForeignKey, text, JSON, TEXT, distinct
from sqlalchemy.orm import Session, relationship
from common.database import Base
from common.database import SessionMixin
from common.utils import is_empty
from core.logger import logger



__all__ = ['NCLogAlarmRecord']

class NCLogAlarmRecord(Base, SessionMixin):
    '''
    日志告警记录表
    '''
    __tablename__ = "nc_log_alarm_record"
    name = Column(String(256), nullable=False, index=True, comment='异常服务名')
    # bigdata、app_server、database
    server_type = Column(String(32), nullable=False, index=True, comment='服务类型')
    classify = Column(String(32), nullable=False, index=True, comment='告警归类')
    # firing / resolved
    alarm_state =Column(String(16), nullable=False, index=True, comment='告警状态')
    alarm_count = Column(Integer, nullable=False, comment='告警次数')
    # [{
    #     "service_name": ""
    #     "alarm_number": "",
    #     "log_type": ""
    #     "error_count": 0
    #     "cst_begin_time": "",
    #     "cst_end_time": "",
    #     "notice_group": [],
    #     "alarm_threshold": "",
    #     "error_message": "",
    #     "app_url": ""
    # }]
    alarm_infos = Column(JSON, nullable=False, default=[], comment='告警信息')
    notice_count = Column(Integer, nullable=True, comment='已通知次数')
    notice_teams_uuid = Column(JSON, nullable=False, default=[], comment='通知小组')
    fingerprint = Column(String(64), nullable=False, index=True, comment='告警指纹')
    starts_at = Column(DateTime, nullable=True, comment='告警开始时间')
    ends_at = Column(DateTime, nullable=True, comment='告警结束时间')
    update_at = Column(DateTime, nullable=False, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    comment = Column(String(256), nullable=True, comment='告警记录说明')


    __table_args__ = (
        {
            'mysql_engine': 'innodb',
            'mysql_charset': 'utf8mb4',
            'mysql_collate': 'utf8mb4_unicode_ci',
            'extend_existing': True,
            'mysql_row_format': 'dynamic',
        }
    )

    def __repr__(self):
        return f"<manage_notice_user='{self.name}': {self.telephone} '>"


    def object_to_dict(self, db: Session):
        result = {
            key: getattr(self, key)
            for key in self.__mapper__.c.keys()
        }
        
        return result



    @classmethod
    def delete_object(cls, db: Session, uuid: int):
        notice_user = cls.get_object_by_uuid(db, uuid)
        notice_user.teams = []
        db.commit()
        notice_user.delete(db)



    @classmethod
    def get_object_info_at_firing(cls, db: Session, name: str):
        """
        获取服务正在告警的记录asc
        """
        object_info = db.query(cls).filter(
            cls.name == name,
            cls.alarm_state == "firing"
        ).order_by(cls.starts_at.desc()).to_dict_first()
        return object_info


    @classmethod
    def get_object_info_all_firing(cls, db: Session):
        """
        获取服务正在告警的记录asc
        """
        object_info = db.query(cls).filter(
            cls.alarm_state == "firing"
        ).to_dict()
        return object_info


    @classmethod
    def get_object_info_for_watchdog(cls, db: Session, watchdog: str):
        """
        获取WatchDog的告警记录
        """
        object_info = db.query(cls).filter(
            cls.name == watchdog,
            cls.alarm_state == "firing"
        ).order_by(cls.update_at.desc()).to_dict()
        if not object_info:
            return {}
        return object_info[0]



